package com.tianji.learning.service.impl;

import com.tianji.api.client.aigc.AIGCClient;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.ReplyDTO;
import com.tianji.learning.domain.po.InteractionQuestion;
import com.tianji.learning.service.AIService;
import com.tianji.learning.service.IInteractionReplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * AI调用相关逻辑业务业务实现类
 *
 * @Author mr.wu
 * @Date 2025-9-5 14:50
 */
@Service
public class AIServiceImpl implements AIService {

    @Autowired
    private AIGCClient aigcClient;

    @Autowired
    private IInteractionReplyService replyService;

    /**
     * AI自动回复
     *
     * @param q
     */
    @Async
    @Override
    public void autoReply(InteractionQuestion q) {
        //1. 调用AIGC服务的feign接口获取用户问题的答案
        String question = String.format("""
                 用户提问的问题标题：%s,
                 用户提问的问题描述：%s,
                 请针对标题和描述进行统一回答
                """,q.getTitle(), q.getDescription());

        UserContext.setUser(q.getUserId());//设置问题里的用户ID，防止出现Feign接口调用401问题
        String reply = aigcClient.text(question);

        //2. 新增问题回复表记录
        ReplyDTO replyDTO = ReplyDTO.builder()
                .userId(9999L) //特殊用户：AI机器人用户
                .content(reply) //问题回复答案
                .isStudent(false)
                .anonymity(false)
                .questionId(q.getId())//关联的问题ID
                .build();
        replyService.saveReply(replyDTO);
    }
}